use crate::db::dao::im_feedback_dao::{feedback_inserts, feedback_total, feedback_updates, query_feedback_by_title};
use crate::db::db::Db;
use crate::db::db_transaction::transaction;
use crate::db::pojo::pojo::ImFeedback;

pub struct ImFeedbackService;

impl ImFeedbackService {

    pub fn save_feedbacks(&self, user_id: String, feedbacks: &mut Vec<ImFeedback>) {
        let db = Db::open();
        let user_id_clone = user_id.clone();
        transaction(db.clone(), move |db: Db| {
            self.save_feedbacks_business(db, user_id_clone, feedbacks)
        });
    }

    pub fn total(&self)->usize {
        let db = Db::open();
        let total = transaction(db.clone(), move |db: Db| {
            feedback_total(db)
        });
        total
    }

    fn save_feedbacks_business(&self, db: Db, user_id: String,  feedbacks: &mut Vec<ImFeedback>) {
        let mut insert_feedback_list= Vec::new();
        let mut update_feedback_list = Vec::new();

        for feedback in feedbacks {
            let db_feedback = query_feedback_by_title(db.clone(), &user_id, &feedback.title);
            if db_feedback.is_some() {
                feedback.id = db_feedback.unwrap().id.clone();
                update_feedback_list.push(feedback);
            } else {
                insert_feedback_list.push(feedback);
            }
        }

        feedback_inserts(db.clone(), &mut insert_feedback_list);
        feedback_updates(db.clone(), &mut update_feedback_list);
    }

}